package machine.utils;

import cn.hutool.json.JSONUtil;
import machine.bean.Msg;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Msg工具类
 *
 * @author zhanghui145
 * @date 2021/12/25 9:54
 * @since 1.0.0
 */
public final class MsgUtils {

    private MsgUtils(){}

    /**
     * request里读取消息实体
     * @param request 请求
     * @return 消息实体
     */
    public static Msg getMsgByRequest(HttpServletRequest request) {
        StringBuilder msg = new StringBuilder();
        try {
            BufferedReader buffer = new BufferedReader(new InputStreamReader(request.getInputStream()));
            boolean flag = true;
            while (flag) {
                String temp = buffer.readLine();
                if (StringUtils.isEmpty(temp)) {
                    flag = false;
                    continue;
                }
                msg.append(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(msg.toString())) {
            return null;
        }
        // System.out.println(msg);
        return JSONUtil.parse(msg).toBean(Msg.class);
    }
}
